import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/Layout'
import store from '@/store'
import { Message } from 'element-ui'

Vue.use(VueRouter)
const whiteList = ['/login', '/register']

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: 'login',
        name: 'login',
        component: () => import('@/views/Login')
      },
      {
        path: 'register',
        name: 'register',
        component: () => import('@/views/Register')
      },
      {
        path: '',
        name: 'column',
        component: () => import('@/views/Column')
      },
      {
        path: 'columns/:userId',
        name: 'user-column',
        component: () => import('@/views/Column/components/UserColumn.vue')
      },
      {
        path: 'column/:columnId',
        name: 'column-detail',
        component: () => import('@/views/Column/components/ColumnDetail.vue')
      },
      {
        path: 'article/:articleId',
        name: 'article',
        component: () => import('@/views/Aticle')
      },
      {
        path: 'add-article',
        name: 'add-article',
        component: () => import('@/views/Aticle/components/AddArticle.vue')
      }
    ]
  },
  {
    path: '/test',
    name: 'test',
    component: () => import('@/views/test.vue')
  },
  {
    path: '*',
    name: 'error',
    component: () => import('@/views/404.vue')
  }
]

const router = new VueRouter({
  routes
})

// 路由前置守卫
router.beforeEach((to, from, next) => {
  const token = store.state.user.token
  if (token) {
    // 已登录但是未获取用户信息
    if (token && !store.state.user.userInfo.nickname) {
    // 获取用户信息
      store.dispatch('user/userInfoActions')
    }
    // 已登录再访问登录或注册页面
    if (token && whiteList.includes(to.path)) {
      next(false)
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path) || to.path === '/') {
      // 白名单放行
      next()
    } else {
      Message.warning('请您先登录!')
      next('/login?redirect=' + encodeURIComponent(to.fullPath))
    }
  }
})

export default router
